package com.liuzhilong.infrastructure.framework.netty.echo.client;

import com.liuzhilong.infrastructure.framework.netty.echo.client.handle.EchoClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.net.InetSocketAddress;
import java.util.concurrent.Semaphore;

@Setter
@Accessors(chain = true)
public class EchoClient {

    private String host;
    private int port;

    public void start() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        Semaphore recived = new Semaphore(1);
        try {
            Bootstrap bootstrap = new Bootstrap(); // 创建 Bootstrap
            bootstrap.group(group) // 指定EventLoopGroup来处理客户端事件。由于我们使用NIO传输，所以用到了 NioEventLoopGroup 的实现
                    .channel(NioSocketChannel.class) // 使用的channel类型是一个用于NIO传输
                    .remoteAddress(new InetSocketAddress(host, port)) // 设置服务器的InetSocketAddr
                    .handler(new ChannelInitializer<SocketChannel>() { // 当建立一个连接和一个新的通道时。创建添加到EchoClientHandler实例到 channel pipeline
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
//                            socketChannel.pipeline().addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
                            recived.acquire();
                            socketChannel.pipeline().addLast("decoder", new StringDecoder());
                            socketChannel.pipeline().addLast("encoder", new StringEncoder());
                            socketChannel.pipeline().addLast(new EchoClientHandler().setSemaphore(recived));
                        }
                    });

            ChannelFuture future = bootstrap.connect(); // 连接到远程；等待连接完成
            future.sync();

            future.channel().writeAndFlush("你好").sync();
//接收到一条回复之后才会关闭
            recived.acquire();


        } finally {
            group.shutdownGracefully().sync(); // 关闭线程池和释放所有资源
        }
    }
}
